package com.sample.navigation.adapter;

import android.view.ViewGroup;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.fragment.app.FragmentTransaction;
import java.lang.reflect.Method;
import java.util.List;

public class NativeFragmentPagerAdapter extends FragmentPagerAdapter{
    private List<Fragment> list;
    private FragmentManager fm;
    private boolean clearCache = false;
    public NativeFragmentPagerAdapter(FragmentManager fm, List<Fragment>list){
        this(fm, 0, list);
    }

    public NativeFragmentPagerAdapter(FragmentManager fm, int behavior, List<Fragment>list){
        this(fm, behavior, list, false);
    }

    public NativeFragmentPagerAdapter(FragmentManager fm, int behavior, List<Fragment>list, boolean clearCache){
        super(fm, behavior);
        this.fm = fm;
        this.list = list;
        this.clearCache = clearCache;
    }
    @Override
    public Fragment getItem(int position) {
        return list.get(position);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
        if (clearCache) {
            removeFragment(container, position);
        }
        return super.instantiateItem(container, position);
    }

    private void removeFragment(ViewGroup container,int index) {
        String tag = getFragmentTag(container.getId(), index);
        Fragment fragment = fm.findFragmentByTag(tag);
        if (fragment == null)
            return;
        FragmentTransaction ft = fm.beginTransaction();
        ft.remove(fragment);
        ft.commitAllowingStateLoss();
        fm.executePendingTransactions();
    }

    private String getFragmentTag(int viewId, int index) {
        try {
            Class<FragmentPagerAdapter> cls = FragmentPagerAdapter.class;
            Class<?>[] parameterTypes = { int.class, long.class };
            Method method = cls.getDeclaredMethod("makeFragmentName",
                    parameterTypes);
            method.setAccessible(true);
            String tag = (String) method.invoke(this, viewId, index);
            return tag;
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }
    }

    @Override
    public int getItemPosition(Object object) {
        return POSITION_NONE;
    }

    @Override
    public int getCount() {
        return list.size();
    }
}
